import 'dart:io';

import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/widgets/button/kq_ink_well.dart';

import '../../resources/kq_theme_colors.dart';
import '../../theme/kq_theme_manager.dart';
import '../divider/kq_divider.dart';
import '../popMenu/kq_popup_menu.dart';
import 'kq_icon_button.dart';

/// 专用于 [KqHeadBar] 左右两边的按钮
///
/// @author 周卓
///
class KqHeadButton<T> extends StatelessWidget {
  /// 按钮类型，文字或图标，默认图标
  final KqHeadButtonType buttonType;

  /// 图标或文字
  final Widget widget;

  /// 弹出菜单Builder
  final List<KqPopMenuItemData>? menuData;

  /// 弹出菜单选中事件
  final OnMenuSelectListener? onSelected;

  /// 点击回调，如果使用了[menuData],则不能用这个，而应该用[onSelected]
  final VoidCallback? onTap;

  /// 弹出气泡的偏移，默认 0,-8
  final Offset? menuOffset;

  /// 气泡菜单最小宽度，默认120
  final double? popMenuMinWidth;

  /// 默认图标类型按钮
  const KqHeadButton(
      {Key? key,
      this.buttonType = KqHeadButtonType.icon,
      required this.widget,
      this.menuData,
      this.popMenuMinWidth,
      this.onSelected,
      this.menuOffset,
      this.onTap})
      : super(key: key);

  /// 默认文字类型按钮
  const KqHeadButton.text(
      {super.key,
      this.buttonType = KqHeadButtonType.text,
      required this.widget,
      this.menuData,
      this.popMenuMinWidth,
      this.onSelected,
      this.menuOffset,
      this.onTap});

  @override
  Widget build(BuildContext context) {

    var iconSize = 40.r;

    if (buttonType == KqHeadButtonType.text) {
      return Container(
        alignment: Alignment.center,
        child: KqInkWell(
          verticalPadding: 10.r,
          radius: 4.r,
          horizontalPadding: 4.r,
          onTap: onTap,
          child: DefaultTextStyle(
            style: TextStyle(
              fontSize: 14.sp,
              color: KqThemeColors.textWhite,
            ),
            child: widget,
          ),
        ),
      );
    }
    if (menuData != null) {
      return SizedBox(
        width: iconSize,
        height: iconSize,
        child: KqPopupMenuButton(
          padding: EdgeInsets.zero,
          splashRadius: iconSize / 2,
          icon: widget,
          offset: menuOffset ?? Offset(0, -4.r),
          elevation: 0,
          position: KqPopupMenuPosition.under,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(8.r)),
          ),
          itemBuilder: (context) {
            return buildItems(menuData!, popMenuMinWidth: popMenuMinWidth);
          },
          onSelected: (entity) {
            if (onSelected != null) {
              onSelected!(entity.position ?? -1, entity);
            }
          },
        ),
      );
    }
    return KqIconButton(
      icon: widget,
      size: iconSize,
      onPressed: onTap,
    );
  }

  static List<KqPopupMenuItem<KqPopMenuItemData>> buildItems(
      List<KqPopMenuItemData> data,
      {double? popMenuMinWidth}) {
    int i = 0;
    for (KqPopMenuItemData e in data) {
      e.position = i;
      i++;
    }
    List<KqPopupMenuItem<KqPopMenuItemData>> list = [];
    for (int j = 0; j < data.length; j++) {
      KqPopMenuItemData item = data[j];
      list.add(KqPopupMenuItem<KqPopMenuItemData>(
        value: item,
        height: 44.r,
        padding: EdgeInsets.zero,
        child: Column(
          children: [
            ConstrainedBox(
              constraints: BoxConstraints(minWidth: popMenuMinWidth ?? 120.r),
              child: SizedBox(
                height: 56.r,
                child: Padding(
                  padding: EdgeInsets.symmetric(horizontal: 16.r),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Visibility(
                        visible: item.imageUrl != null &&
                            item.imagePosition == KqPopMenuImagePosition.left,
                        child: Container(
                          margin: EdgeInsets.only(right: 12.r),
                          child: Align(
                            child: item.customImage ??
                                Image.asset(
                                  item.imageUrl ?? "",
                                  width: 28.r,
                                  height: 28.r,
                                  fit: BoxFit.fill,
                                  colorBlendMode:
                                      item.autoIconColor ? BlendMode.srcIn : null,
                                  color: item.autoIconColor
                                      ? (KqThemeManager.getButtonConfig()
                                                  .headButtonMenuIconColor ??
                                              KqThemeColors.text26)
                                          .withOpacity(
                                              item.hasPermission ? 1.0 : 0.25)
                                      : null,
                                ),
                          ),
                        ),
                      ),
                      Text(
                        item.title,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            fontSize: item.fontSize ??
                                KqThemeManager.getButtonConfig()
                                    .headButtonMenuFontSize ??
                                14.sp,
                            color: (item.textColor ??
                                    KqThemeManager.getButtonConfig()
                                        .headButtonMenuTextColor ??
                                    KqThemeColors.text26)
                                .withOpacity(item.hasPermission ? 1.0 : 0.25)),
                      ),
                      Visibility(
                        visible: item.imageUrl != null &&
                            item.imagePosition == KqPopMenuImagePosition.right,
                        child: Container(
                          margin: EdgeInsets.only(left: 12.r),
                          child: item.customImage ??
                              Image.asset(
                                item.imageUrl ?? "",
                                width: 28.r,
                                height: 28.r,
                                fit: BoxFit.fill,
                                colorBlendMode:
                                    item.autoIconColor ? BlendMode.srcIn : null,
                                color: item.autoIconColor
                                    ? (KqThemeManager.getButtonConfig()
                                                .headButtonMenuIconColor ??
                                            KqThemeColors.text26)
                                        .withOpacity(
                                            item.hasPermission ? 1.0 : 0.25)
                                    : null,
                              ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
            Visibility(
                visible: j < data.length - 1,
                child: KqDivider(
                  height: 0.5,
                  leftMargin: item.imageUrl == null ? 16.r : 50.r,
                  color: KqThemeColors.bgF0,
                ))
          ],
        ),
      ));
    }
    return list;
  }
}

/// 菜单选中
typedef OnMenuSelectListener = void Function(
    int position, KqPopMenuItemData entity);

enum KqHeadButtonType {
  /// 按钮类型
  text,

  /// 文字
  icon
}

class KqPopMenuItemData {
  int? position;

  /// 标题
  String title;

  /// 图片路径，不传则不显示图标
  String? imageUrl;

  /// 自定义图片控件，优先级大于[imageUrl]
  Widget? customImage;

  /// 图片位置，默认左边
  KqPopMenuImagePosition imagePosition;

  /// 是否自动改变图标颜色，false则使用图标原本颜色，默认为true
  bool autoIconColor;

  /// 是否有权限，无权限则使用无权限的图标和文字颜色，默认为false
  bool hasPermission;

  /// 字体大小，不传则默认使用主题配置的字体大小
  double? fontSize;

  /// 文字颜色，特殊情况下使用，一般不用传
  Color? textColor;

  /// 背景颜色，特殊情况下使用，一般不用传
  Color? bgColor;

  /// 自定义内容，可用作[onSelected]时唯一标识这个菜单，有时候菜单是动态隐藏和显示的，用[position]不准确
  dynamic extraData;

  KqPopMenuItemData(
      {required this.title,
      this.imageUrl,
      this.fontSize,
      this.customImage,
      this.imagePosition = KqPopMenuImagePosition.left,
      this.hasPermission = false,
      this.autoIconColor = true,
      this.textColor,
      this.bgColor,
      this.extraData});
}

enum KqPopMenuImagePosition {
  left,
  right,
}
